package com.hkbigdata.sybx.controller;

import com.hkbigdata.sybx.bean.UserIdentity;
import com.hkbigdata.sybx.mapper.UserIdentityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yangjing
 * @creat 2025-06-04-11:26
 * @email 3010335359@qq.com
 */

@RestController
@RequestMapping("/api/userIdentity")
public class UserIdentityController {

    @Autowired
    private UserIdentityMapper identityMapper;

    /**
     * 添加用户实名信息
     */
    @PostMapping("/insert")
    public Map<String, Object> addUserIdentity(@RequestBody UserIdentity identity) {
        Map<String, Object> result = new HashMap<>();

        // 检查参数完整性
        if (identity.getUserId() == null || identity.getRealName() == null || identity.getIdCard() == null) {
            result.put("success", false);
            result.put("message", "缺少必要参数");
            return result;
        }

        // 检查用户是否已实名
        UserIdentity existsIdentity = identityMapper.getUserIdentityByUserId(identity.getUserId());
        if (existsIdentity != null) {
            result.put("success", false);
            result.put("message", "该用户已完成实名认证，不能重复添加");
            return result;
        }

        // 检查身份证号是否已被使用
        UserIdentity idCardExists = identityMapper.getUserIdentityByIdCard(identity.getIdCard());
        if (idCardExists != null) {
            result.put("success", false);
            result.put("message", "该身份证号已被其他用户使用");
            return result;
        }

        try {
            int rows = identityMapper.addUserIdentity(identity);
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "实名认证成功");
                result.put("data", identity);
            } else {
                result.put("success", false);
                result.put("message", "实名认证失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "实名认证异常：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 通过userId查询用户实名信息
     */
    @GetMapping("/{userId}")
    public Map<String, Object> getUserIdentity(@PathVariable String userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            UserIdentity identity = identityMapper.getUserIdentityByUserId(userId);
            if (identity != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", identity);
            } else {
                result.put("success", false);
                result.put("message", "未找到该用户的实名信息");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}
